
<?php
$host = '0.0.0.0';
$port = 6666;
$listen_socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
socket_set_option( $listen_socket, SOL_SOCKET, SO_REUSEADDR, 1 );
socket_set_option( $listen_socket, SOL_SOCKET, SO_REUSEPORT, 1 );
socket_bind( $listen_socket, $host, $port );
socket_listen( $listen_socket );
socket_set_nonblock( $listen_socket );
$client_arr = array();
$event_arr  = array();
$client_arr[ intval( $listen_socket ) ] = $listen_socket;


$event_config = new EventConfig();
$event_base   = new EventBase( $event_config );
$event = new Event( $event_base, $listen_socket, Event::READ | Event::PERSIST, 'ev_accept', $event_base );
$event->add();
$event_base->loop();


function ev_read( $event_buffer_event, $connect_socket ) {
    global $client_arr;
    global $event_arr;
    $recv_content = $event_buffer_event->read( 1024 );
    echo "read cb : ".$recv_content;
    //$event_buffer_event->readBuffer( $recv_content );
}

function ev_accept( $listen_socket, $what, $event_base ) {
    global $client_arr;
    global $event_arr;
    // accept后，listen-socket上的可读事件将会被清空
    $connect_socket = socket_accept( $listen_socket );
    socket_set_nonblock( $connect_socket );
    if ( !$connect_socket ) {
        return;
    }
    // 按照以往，我们在这里注册ev_read事件回调
    // 然而现如今，我们不能再用Event了
    // 而是需要用EventBufferEvent来代替传统的Event类
    // 也就是带有EventBuffer功能的增强版的Event类
    //$client_event = new Event( $event_base, $connect_socket, Event::READ | Event::PERSIST, 'ev_read', $event_base );
    //$client_event->add();
    // 这个是EventBufferEvent的初始化方法，大家可以参考文档里原型
    // 我就不再赘述原型了

    $client_event = new EventBufferEvent( $event_base, $connect_socket, 0 );
    // 设置回调，我们先研究读事件
    // 这里只设置了读事件回调


    $client_event->setCallbacks( 'ev_read', NULL, NULL, $connect_socket );
    $client_event->setTimeouts( 30, 30 );
    // 给读缓冲区设置 低水位 和 高水位
    $client_event->setWatermark( Event::READ, 4, 6 );
    $client_event->setPriority( 10 );
    $client_event->enable( Event::READ );
    $client_arr[ intval( $connect_socket ) ] = $connect_socket;
    $event_arr[ intval( $connect_socket ) ]  = $client_event;
}
